package config

import (
	"strconv"
	"strings"
)

func init()  {
	doLoad()
}

var prop = make(map[any]any)

func Set(key string, val any) {
	// TODO
}

func GetString(key string, defaultValue string) string {
	return get(key, defaultValue).(string)
}

func GetInt(key string, defaultValue int) int {
	value := get(key, defaultValue)
	switch value.(type) {
	case string:
		value, _ = strconv.Atoi(value.(string))
		return value.(int)
	default:
		return value.(int)
	}
}

func GetArray[T any](key string) []T {
	value := get(key, nil)
	switch value.(type) {
	case []any:
		oldArr := value.([]any)
		newArr := make([]T, len(oldArr))
		for i, v := range oldArr {
			newArr[i] = v.(T)
		}
		return newArr
	default:
		return nil
	}
}

func get(key string, defaultValue interface{}) interface{} {
	keys := strings.Split(key, ".")

	var value interface{} = prop

	for _, v := range keys {
		if value == nil {
			return defaultValue
		}

		switch value.(type) {
		case map[interface{}]interface{}:
			value = value.(map[interface{}]interface{})[v]
		case map[string]interface{}:
			value = value.(map[string]interface{})[v]
		default:
			return value
		}
	}

	if value == nil {
		return defaultValue
	}

	return value
}
